<!DOCTYPE html>
<html>
  <head>
    <title>WebSocket Test</title>  
    <style>
    </style>
</head>
    <body>

  <h2>WebSocket Test</h2>

  <div id="output">
  </div>
<input type="text" id="msg">
  <button id="send" onclick="send()">发送</button>
  <button id="sendFile" onclick="sendFile()">发送文件</button>
  <script>

    var wsUri = "ws://localhost:23618/ws";
    var output;
    var websocket;
    var inputNode = document.getElementById('msg');

    function writeToScreen(message)
    {
      var pre = document.createElement("p");
      pre.innerHTML = message;
      output.appendChild(pre);
    }
    function send(){
      // 发送
      console.log('send click')
      var v = inputNode.value;
      const message = {
        msg: v,
        name: 'John',
        age: 30,
      };
      var m = JSON.stringify(message);
      doSend(m)
    }
        function sendFile(){
      // 发送
      console.log('send File click')
      var v = inputNode.value;
      const message = {
        msg: v,
        name: 'John',
        age: 30,
      };
      var m = JSON.stringify(message);
      doSend(m)
    }

    function doSend(message)
    {
      
      websocket.send(message);      
      writeToScreen("SENT: " + message);
    }
    function doSendFile(message)
    {
      
      websocket.send(message);      
      writeToScreen("SENT: " + message);
    }
    function onOpen(evt)
    {
      writeToScreen("CONNECTED");
      doSend("WebSocket rocks");
    }

    function onClose(evt)
    {
      writeToScreen("DISCONNECTED");
    }

    function onMessage(evt)
    {
      
      if (typeof event.data === "string") {
    // 收到文本消息
    console.log("Received text message:", event.data);
    writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
    var data = JSON.parse(event.data)
    console.log(data)
    if(data.data){
        
    }
  } else if (event.data instanceof Blob) {
    // 收到二进制消息（Blob 对象）
    console.log("Received binary message");

    // 创建新的图片元素
    const img = document.createElement("img");

    // 将接收到的二进制图片数据转换为DataURL
    const urlCreator = window.URL || window.webkitURL;
    const imageUrl = urlCreator.createObjectURL(event.data);

    // 设置图片src为DataURL，显示图片
    img.src = imageUrl;
    //document.body.appendChild(img);
    //writeToScreen(img);
    writeToScreen('<img style="width: 100px;height:100px;" src="'+img.src+'"></img> ');
  }
      //websocket.close();
      //websocket = null;
    }

    function onError(evt)
    {
      writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
    }

    function testWebSocket()
    {
      websocket = new WebSocket(wsUri);
      websocket.onopen = function(evt) { onOpen(evt) };
      websocket.onclose = function(evt) { onClose(evt) };
      websocket.onmessage = function(evt) { onMessage(evt) };
      websocket.onerror = function(evt) { onError(evt) };
    }

    output = document.getElementById("output");
    testWebSocket();

  </script>
  </body>  
</html>